﻿using System;
using System.Web;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace Utility
{
    public static class Utility
    {
        public static dynamic GetJson(string url, HttpMethod httpMethod, Dictionary<string, string> queryString, object postJson = null)
        {
            if (url != null && url.Contains("?"))
                url = url.Split('?')[0];
            if (string.IsNullOrWhiteSpace(url))
                throw new Exception("URL supplied was invalid");

            var urlBuilder = new StringBuilder(url);
            var qs = string.Empty;

            if (queryString != null)
            {
                var qsParams = new List<string>();
                foreach (var qsParam in queryString.Keys)
                {
                    var sb = new StringBuilder();
                    sb.Append(qsParam);
                    sb.Append("=");
                    sb.Append(HttpUtility.UrlEncode(queryString[qsParam]));
                    qsParams.Add(sb.ToString());
                }
                qs = string.Join("&", qsParams);
            }
            urlBuilder.Append("?");
            urlBuilder.Append(qs);
            url = urlBuilder.ToString();

            if (httpMethod == HttpMethod.Get)
            {
                using (var httpClient = new HttpClient())
                {
                    var response = httpClient.GetAsync(url).Result;
                    return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
                }
            }
            else if (httpMethod == HttpMethod.Post)
            {
                string json = JsonConvert.SerializeObject(postJson);

                using (var httpClient = new HttpClient())
                {
                    var response = httpClient.PostAsync(url, new StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
                    return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
                }
            }

            return new {};
        }
        public static DateTime UnixTimeStampToDateTime(string unixTimeStamp)
        {
            long uts = long.Parse(unixTimeStamp);
            // Unix timestamp is seconds past epoch
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddSeconds(uts).ToLocalTime();
            return dtDateTime;
        }
    }
}
